package tom.oauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import tom.oauth2.service.BaseUserDetailService;

/**
 * spring-security配置
 * @author ZHUFEIFEI
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //登陆成功后的允许访问所有授权请求
//        http.authorizeRequests().anyRequest().fullyAuthenticated();
        //设置登陆的url和登陆成功失败跳转的url
//        http.formLogin().loginPage("/login").defaultSuccessUrl("/").failureUrl("/login?code=").permitAll();
//        http.formLogin();
        //授权码请求允许任何人访问
//        http.authorizeRequests().antMatchers("/oauth/authorize").permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //设置忽略规则
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/druid/**");
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        return new BaseUserDetailService();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        //密码处理器，该方法创建一系列的处理器根据前缀来选择使用哪个类处理
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    public TokenStore tokenStore(RedisConnectionFactory redisConnectionFactory) {
        return new RedisTokenStore(redisConnectionFactory);
    }
}
